// pages/chatting.js
const app = getApp()

import {im_sendMessage, im_getMessageList, im_setMessageRead} from '../../utils/tim_utils'
import {end_nowAdvising, upload_comment} from '../../utils/backend'

const recorderManager = wx.getRecorderManager();//全局录音管理器（收发语音消息需要使用）
const recordOptions = {// 录音部分参数
  duration: 60000, // 录音的时长，单位 ms，最大值 600000（10 分钟）
  sampleRate: 44100, // 采样率
  numberOfChannels: 1, // 录音通道数
  encodeBitRate: 192000, // 编码码率
  format: 'aac' // 音频格式
};

const innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = false
innerAudioContext.src = ''//动态更改

Page({

  /**
   * 页面的初始数据
   */
  data: {
    nbTitle: '在线咨询',
    TopBar: 90,//顶栏高度
    HalfTopBar: 45,//顶栏高度/2
    ImageSize: 70,//咨询师头像高度
    MarginSmall: 10,//纵向边缘距离
    MarginBig: 20,//横向边缘距离

    voice:false,//是否发送声音
    is_recording:false,//是否正在录音
    innerAudioContext:'',//音频播放管理器
    is_playing:false,//是否正在播放
    playing_uuid:'',//正在播放中的语音的UUID
    emojis:false,//是否发送表情
    camera:false,//是否发送图片
    sendout:true,//是否发送完成
    pression:[//emoji表情
      '😀','😃','😄','😁','😆','😅','😂','🤣','☺️','😊','😇','🙂','🙃','😉','😌','😍','🥰','😘','😗','😙','😚','😋','😛','😝','😜','🤪','🤨','🧐','🤓','😎','🤩','🥳','😏','😒','😞','😔','😟','😕','🙁','☹️','😣','😖','😫','😩','🥺','😢','😭','😤','😠','😡','🤬','🤯','😳','🥵','🥶','😱','😨','😰','😥','😓','🤗','🤔','🤭','🥱','🤫','🤥','😶','😐','😑','😬','🙄','😯','😦','😧','😮','😲','😴','🤒','🤕','🤑','🤠','😈','👿','👹','👺','🤡'
    ],

    // im实时聊天数据
    userID: '',
    userImage: '',
    //本次咨询相关数据
    advisorInfo:{},
    created:'',
    ended:'',
    score:'',
    comment:'',
    confirm:false,
    
    advisorInputting: false,//咨询师是否正在输入
    timer: '',

    //聊天消息相关
    toView:'',
    my_message:'',
    msgList: [],
    nextReqMessageID: '',
    isCompleted: ''//消息记录拉取完成
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showNavigationBarLoading() //显示Loading圆圈
    //1.获取全局数据
    this.setData({
      userID: app.globalData.userInfo.id,
      userImage: app.globalData.userInfo.image
    })
    
    //2.获取咨询相关数据（数据包括：1.聊天开始的时间戳created，2.咨询师信息advisorInfo）
    this.setData({
      created: app.globalData.nowAdvising.created,
      ended: app.globalData.nowAdvising.ended,
      advisorInfo: app.globalData.nowAdvising.advisorInfo,
    })
    wx.event.on("creat_advising_and_save_to_global",()=>{
      this.setData({
        created: app.globalData.nowAdvising.created,
        ended: app.globalData.nowAdvising.ended,
        advisorInfo: app.globalData.nowAdvising.advisorInfo,
      })
    })

    //3. 初始化消息列表并渲染
    wx.event.on('renderMsgList',(e,nextReqMessageID,isCompleted)=>{//订阅初始化获取聊天记录后渲染至页面
      let list = this.data.msgList
      list= [...e]
      this.setData({
        msgList : list,
        nextReqMessageID : nextReqMessageID,
        isCompleted : isCompleted
      },()=>{
        that.scrollToBottom()
      })
      im_setMessageRead(this.data.advisorInfo.id)
    })
    wx.event.on('renderMsg',(e,newMsgForm)=>{//订阅renderMsg事件来渲染页面
      let newMsgObj = e;
      if(newMsgForm == this.data.advisorInfo.id){
        this.setData({
          msgList : that.data.msgList.concat([newMsgObj])
        },()=>{
          that.scrollToBottom()
        })
      }
      im_setMessageRead(this.data.advisorInfo.id)
    })
    

    //4.初始化录音管理器
    var that = this
    recorderManager.onError(function(errMsg) {//录音出错
      console.warn('recorder error:', errMsg);
    });
    recorderManager.onStop(function(res) {//录音结束
      console.log('recorder stop', res);
      console.log("========== duration: "+res.duration+"==========")
      if(res.duration<=1000){
        wx.showToast({
          title: '说话时间太短',
          icon: 'error'
        })
      }else{
        im_sendMessage(that.data.advisorInfo.id+'', res, 'audio')
      }
    });

    //5.初始化音频播放管理器
    this.setData({
      innerAudioContext: innerAudioContext
    })
    innerAudioContext.onPlay(() => {
      this.setData({
        is_playing:true,
      })
      console.log("========== innerAudioContext: play ==========")
    })
    innerAudioContext.onError((res) => {
      this.setData({is_playing:false})
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    innerAudioContext.onStop((res)=>{
      this.setData({
        is_playing:false,
        playing_uuid:''
      })
      console.log("========== innerAudioContext: stop ==========")
    })
    innerAudioContext.onEnded((res)=>{
      this.setData({
        is_playing:false,
        playing_uuid:''
      })
      console.log("========== innerAudioContext: end ==========")
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideNavigationBarLoading() //隐藏Loading圆圈
    this.setData({
      ended: app.globalData.nowAdvising.ended
    })

    //若待发送的咨询记录列表不为空，则发送、并置空
    for(var i=0; i<app.globalData.chosenRecordList.length; i++){
      im_sendMessage(this.data.advisorInfo.id+'', app.globalData.chosenRecordList[i], 'record')
    }
    app.globalData.chosenRecordList=[]

    //若咨询没有结束则轮询更新时长
    var that = this
    var time_interval = setInterval(function(){
      if(that.data.ended!=''&&that.data.ended!=null){
        clearInterval(time_interval)
      }
      var timestamp = Date.parse(new Date())
      //当前时间戳  
      var diff = (parseInt(timestamp/1000) - that.data.created)
      var h = parseInt(diff/3600)
      var m = (parseInt(diff/60))%60
      var s = diff%60
      that.setData({
        timer: (h>9?h:'0'+h)+':'+(m>9?m:'0'+m)+':'+(s>9?s:'0'+s)
      })
    },1000)

    //订阅初始化获取聊天记录
    wx.event.on('conversationInit',()=>{
      im_getMessageList(this.data.advisorInfo.id);
    })
    

    wx.event.emit('conversationInit')
  },


  speak:function(){// 点击语音按钮
    this.setData({
      voice:!this.data.voice,
      emojis:false,
      camera:false,
    })
  },

  emoji:function(){// 点击表情按钮
    this.setData({
      emojis:!this.data.emojis,
      voice:false,
      camera:false,
    })
  },

  pick_emoji:function(e){// 输入表情
    let item = e.currentTarget.dataset.item
    this.setData({
      sendout: false,
      my_message: this.data.my_message + item,
    })
  },

  camerax:function(){// 点击加号按钮
    this.setData({
      camera:!this.data.camera,
      voice:false,
      emojis:false
    })
  },

  message:function(e){// 点击“发送”按钮
    // 1.发送消息
    im_sendMessage(this.data.advisorInfo.id+'', this.data.my_message, 'text')
    // 2.恢复布局
    this.setData({
      sendout:true,//消息发送成功
      my_message:'',//待发送消息置空
    })
  },

  mon_input(e){// 监听文字输入框の输入
    var that=this;
    var content=e.detail.value;
    that.setData({
      my_message: content,
      sendout: content==''?true:false,
    })
  },

  getkey:function(e){// 焦点在输入框
    this.setData({
      emojis:false,
      camera:false
    })
  },

  getblur:function(e){// 焦点离开输入框
    this.setData({
      emojis:false,
      camera:false,
      voice:false,
    })
  },

  upload:function(e){// 发送图片
    // 1. 选择图片
    let that = this
    wx.chooseImage({
      sourceType: ['album'], // 从相册选择
      count: 1, // 只选一张，目前SDK不支持一次发送多张图片
      success: function (res) {
        // 2. 创建消息实例，接口返回的实例可以上屏
        im_sendMessage(that.data.advisorInfo.id+'', res, 'image')
      }
    })
  },

  scrollToBottom() {//聊天区域滑动至底部
    let that = this;
    this.setData({
      toView: 'msg-' + (this.data.msgList.length - 1)
    })
  },

  tapChatArea(){//点击聊天消息区域
    this.setData({
      emojis:false,
      camera:false,
    })
  },

  imagePreview(e){//点击聊天区域的图片——图片预览
    var currentUrl = e.currentTarget.dataset.src
    wx.previewImage({
      current: currentUrl,
      urls: [currentUrl]
    })
  },

  touchDown(){//长按“按住说话”开始
    console.log('==========touch down==========')
    this.setData({
      is_recording: true
    })
    recorderManager.start(recordOptions);
  },

  touchUp(){//长按“按住说话”结束
    console.log('==========touch up==========')
    recorderManager.stop();
    this.setData({
      is_recording: false
    })
  },

  playAudio(e){//点击语音消息
    if(!this.data.is_playing){//播放
      this.data.innerAudioContext.src=e.currentTarget.dataset.src
      this.data.innerAudioContext.play()
      this.setData({
        playing_uuid: e.currentTarget.dataset.uuid
      })
    }else{//取消播放
      this.data.innerAudioContext.stop()
    }
  },

  finishAdvising(){//结束咨询：1.弹窗是否结束；2.确定结束时记录时间
    //弹窗询问用户是否要结束咨询
    var that = this
    wx.showModal({
      title: '提示',
      content: '是否结束咨询？',
      success (res) {
        if (res.confirm) {//确定结束：记录结束时间，上传至服务器（上传成功后开始评价）
          var timestamp = Date.parse(new Date())
          end_nowAdvising(timestamp)
          wx.event.on("upload_end_timestamp_done",()=>{
            that.setData({
              ended: parseInt(timestamp/1000),
              toView: 'rater'
            },()=>{
              that.scrollToBottom()
            })
            app.globalData.nowAdvising.ended = that.data.ended
            wx.showToast({
              title: "咨询已结束，点评一下吧~",
              icon:'none'
            })
          })
        }
      }
    })
  },

  starRater(e){//点击星星进行评分
    var star = e.currentTarget.dataset.id
    if(!this.data.confirm){
      switch(star){
        case 'star1': 
          this.setData({score:1}); break;
        case 'star2': 
          this.setData({score:2}); break;
        case 'star3': 
          this.setData({score:3}); break;
        case 'star4': 
          this.setData({score:4}); break;
        case 'star5': 
          this.setData({score:5}); break;
      }
    }
  },

  uploadComment(){//提交评分，上传本次咨询
    if(!(this.data.score>0)){
      wx.showToast({
        title: '请点击评分后再提交哦~',
        icon:'none'
      })
    }else{
      this.setData({confirm:true})
      upload_comment(this.data.score, this.data.comment)
      wx.event.on("upload_comment_done",()=>{
        wx.navigateBack({
          delta:1,
          success(){
            wx.showToast({
              title: '评分已提交',
              icon:'success'
            })
          }
        })
      })
    }  
  },

  mon_comment_input(e){
    var comment=e.detail.value;
    this.setData({
      comment: comment
    })
  },

  sendRecord(){
    console.log("========== send record ==========");
    wx.navigateTo({
      url: '../choose_advising/choose_advising',
    })
  },

  recordPreview(e){
    var record = e.currentTarget.dataset.record
    console.log(record)
    var advisorInfoBean = JSON.stringify(record.advisorInfo)
    var created = record.created
    wx.navigateTo({
      url: '/pages/message/message?advisorInfoBean='+advisorInfoBean+'&created='+created,//将咨询师信息传至聊天记录页面并跳转
    })
  }
})